package com.example.pathtracker.activity

import android.Manifest
import android.content.pm.PackageManager
import android.graphics.Color
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.amap.api.maps.AMap
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.BitmapDescriptorFactory
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.MarkerOptions
import com.amap.api.maps.model.MyLocationStyle
import com.amap.api.maps.model.PolylineOptions
import com.example.pathtracker.bean.MapPoint
import com.example.pathtracker.bean.PathData
import com.example.pathtracker.bean.PointType
import com.example.pathtracker.bean.PointTypeData
import com.example.pathtracker.bean.UploadResponse
import com.example.pathtracker.bean.PathTypeData
import com.example.pathtracker.databinding.ActivityMapOverviewBinding
import com.example.pathtracker.net.RetrofitClient
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import com.bumptech.glide.Glide
import java.util.concurrent.Executors
import android.app.AlertDialog
import com.amap.api.maps.model.Marker

class MapOverviewActivity : AppCompatActivity(), AMapLocationListener {
    private lateinit var binding: ActivityMapOverviewBinding
    private lateinit var aMap: AMap
    private lateinit var locationClient: AMapLocationClient
    private var isFirstLocation = true
    private var pointTypeList: List<PointTypeData> = emptyList()
    private val pointList = mutableListOf<MapPoint>()
    private var currentPaths: List<PathData> = emptyList()
    private var currentPathTypes: List<PathTypeData> = emptyList()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMapOverviewBinding.inflate(layoutInflater)
        setContentView(binding.root)
        supportActionBar?.title = "全览地图"
        supportActionBar?.setDisplayHomeAsUpEnabled(true) // 显示返回按钮
        binding.mapView.onCreate(savedInstanceState)
        aMap = binding.mapView.map
        setupMap()
        setupMapClickListeners()
        checkPermissions()
        initLocation()
        loadAllData()
    }

    private fun setupMap() {
        // 设置地图基本配置
        aMap.uiSettings.isZoomControlsEnabled = true
        aMap.uiSettings.isMyLocationButtonEnabled = false // 隐藏定位按钮
        
        // 设置定位样式
        val myLocationStyle = MyLocationStyle()
            .showMyLocation(true)
            .myLocationType(MyLocationStyle.LOCATION_TYPE_SHOW)
        
        aMap.apply {
            setMyLocationStyle(myLocationStyle)
            isMyLocationEnabled = true
        }
    }
    private val markerMap = mutableMapOf<Marker, MapPoint>()
    private fun setupMapClickListeners() {
        // 设置标记点击监听器
        aMap.setOnMarkerClickListener { marker ->



            marker?.let {
                showPointInfoDialog(marker)
            }
            true
        }
    }

    private fun showPointInfoDialog(marker: Marker) {

        val point = markerMap[marker] ?: return

        val message = """
            点位名称: ${point.pointName}
            点位类型: ${point.typeName}
            联系方式: ${point.phone}
            经纬度: ${point.lat}, ${point.lng}
        """.trimIndent()
        AlertDialog.Builder(this)
            .setTitle(point.pointName)
            .setMessage(message)
            .setNegativeButton("关闭", null)
            .show()
    }

    private fun checkPermissions() {
        val permissions = arrayOf(
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
        )

        val permissionsToRequest = permissions.filter {
            ContextCompat.checkSelfPermission(this, it) != PackageManager.PERMISSION_GRANTED
        }.toTypedArray()

        if (permissionsToRequest.isNotEmpty()) {
            ActivityCompat.requestPermissions(this, permissionsToRequest, PERMISSION_REQUEST_CODE)
        }
    }

    private fun initLocation() {
        try {
            locationClient = AMapLocationClient(applicationContext)
            locationClient.setLocationListener(this)

            val locationOption = AMapLocationClientOption().apply {
                locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
                interval = 2000
                isNeedAddress = true
                isOnceLocation = true // 只定位一次
            }
            locationClient.setLocationOption(locationOption)
            locationClient.startLocation()
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(this, "定位初始化失败", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onLocationChanged(location: AMapLocation?) {
        location?.let {
            if (it.errorCode == 0) {
                val latLng = LatLng(it.latitude, it.longitude)
                if (isFirstLocation) {
                    aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 14f))
                    isFirstLocation = false
                    locationClient.stopLocation()
                }
            } else {
                Toast.makeText(this, "定位失败: ${it.errorInfo}", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun loadAllData() {
        // 先获取路径类型，然后再获取路径列表
        RetrofitClient.apiService.getAllPathType().enqueue(object : Callback<UploadResponse<List<PathTypeData>>> {
            override fun onResponse(
                call: Call<UploadResponse<List<PathTypeData>>>,
                response: Response<UploadResponse<List<PathTypeData>>>
            ) {
                if (response.isSuccessful) {
                    response.body()?.data?.let { pathTypes ->
                        // 保存路径类型列表并过滤无效数据
                        val validPathTypes = pathTypes.filter { 
                            it != null && !it.lineColor.isNullOrEmpty() && it.id != null 
                        }
                        android.util.Log.d("MapOverviewActivity", "获取到${validPathTypes.size}个有效路径类型")
                        // 获取到路径类型后，再获取路径列表
                        loadPaths(validPathTypes)
                    } ?: run {
                        android.util.Log.e("MapOverviewActivity", "路径类型数据为空")
                        Toast.makeText(this@MapOverviewActivity, "获取路径类型失败：数据为空", Toast.LENGTH_SHORT).show()
                    }
                } else {
                    android.util.Log.e("MapOverviewActivity", "获取路径类型失败：${response.code()}")
                    Toast.makeText(this@MapOverviewActivity, "获取路径类型失败：${response.code()}", Toast.LENGTH_SHORT).show()
                }
            }
            override fun onFailure(call: Call<UploadResponse<List<PathTypeData>>>, t: Throwable) {
                android.util.Log.e("MapOverviewActivity", "获取路径类型失败", t)
                Toast.makeText(this@MapOverviewActivity, "获取路径类型失败: ${t.message}", Toast.LENGTH_SHORT).show()
            }
        })
        
        // 获取点位类型和点位
        getPointTypeListAndPoints()
    }

    private fun loadPaths(pathTypes: List<PathTypeData>) {
        if (pathTypes.isEmpty()) {
            android.util.Log.w("MapOverviewActivity", "没有有效的路径类型，跳过加载路径")
            return
        }

        RetrofitClient.apiService.getAllPaths().enqueue(object : Callback<UploadResponse<List<PathData>>> {
            override fun onResponse(
                call: Call<UploadResponse<List<PathData>>>,
                response: Response<UploadResponse<List<PathData>>>
            ) {
                if (response.isSuccessful) {
                    response.body()?.data?.let { paths ->
                        android.util.Log.d("MapOverviewActivity", "获取到${paths.size}条路径")
                        if (paths.isNotEmpty()) {
                            currentPaths = paths
                            currentPathTypes = pathTypes
                            runOnUiThread {
                                drawAllPaths(paths, pathTypes)
                            }
                        } else {
                            android.util.Log.w("MapOverviewActivity", "没有路径数据")
                        }
                    } ?: run {
                        android.util.Log.e("MapOverviewActivity", "路径数据为空")
                        Toast.makeText(this@MapOverviewActivity, "获取路径失败：数据为空", Toast.LENGTH_SHORT).show()
                    }
                } else {
                    android.util.Log.e("MapOverviewActivity", "获取路径失败：${response.code()}")
                    Toast.makeText(this@MapOverviewActivity, "获取路径失败：${response.code()}", Toast.LENGTH_SHORT).show()
                }
            }
            override fun onFailure(call: Call<UploadResponse<List<PathData>>>, t: Throwable) {
                android.util.Log.e("MapOverviewActivity", "获取路径失败", t)
                Toast.makeText(this@MapOverviewActivity, "获取路径失败: ${t.message}", Toast.LENGTH_SHORT).show()
            }
        })
    }

    private fun drawAllPaths(paths: List<PathData>, pathTypes: List<PathTypeData>) {
        try {
            android.util.Log.d("MapOverviewActivity", "开始绘制路径，共 ${paths.size} 条")
            
            var successCount = 0
            var failureCount = 0
            // Clear only polylines, not markers
//            aMap.clear(true)  // Clear everything first to avoid duplicates
            for (path in paths) {
                try {
                    // 数据验证
                    if (path.latlon.isNullOrEmpty()) {
                        android.util.Log.w("MapOverviewActivity", "路径坐标为空：${path.pathName}")
                        failureCount++
                        continue
                    }

                    // 解析坐标点
                    val coordinates = try {
                        com.google.gson.Gson().fromJson(path.latlon, Array<Array<Double>>::class.java)
                    } catch (e: Exception) {
                        android.util.Log.e("MapOverviewActivity", "解析坐标失败: ${path.latlon}", e)
                        failureCount++
                        continue
                    }

                    // 转换坐标点为LatLng列表
                    val points = coordinates.mapNotNull { coordinate ->
                        try {
                            if (coordinate.size >= 2 && 
                                coordinate[0] != 0.0 && coordinate[1] != 0.0) {
                                LatLng(coordinate[1], coordinate[0]) // 纬度,经度
                            } else {
                                null
                            }
                        } catch (e: Exception) {
                            android.util.Log.e("MapOverviewActivity", "坐标转换失败", e)
                            null
                        }
                    }

                    if (points.size >= 2) {
                        // 查找路径类型
                        val pathType = pathTypes.find { it.id.toString() == path.typeId }
                        
                        // 设置路径样式
                        val color = pathType?.let {
                            try {
                                Color.parseColor(it.lineColor)
                            } catch (e: Exception) {
                                Color.BLUE
                            }
                        } ?: Color.BLUE

                        val isDotted = pathType?.lineType == "1"
                        
                        // 创建并添加路线
                        val polylineOptions = PolylineOptions().apply {
                            addAll(points)
                            width(10f)
                            color(color)
                            setDottedLine(isDotted)
                            geodesic(true)  // 使用大地线
                        }
                        
                        // 添加到地图
                        val polyline = aMap.addPolyline(polylineOptions)
                        
                        android.util.Log.d("MapOverviewActivity", 
                            "绘制路径成功: ${path.pathName}, 点数: ${points.size}, " +
                            "颜色: ${String.format("#%06X", 0xFFFFFF and color)}, " +
                            "是否虚线: $isDotted")
                        
                        successCount++
                    } else {
                        android.util.Log.w("MapOverviewActivity", "路径点数不足：${points.size}")
                        failureCount++
                    }
                } catch (e: Exception) {
                    android.util.Log.e("MapOverviewActivity", "绘制路径失败: ${path.pathName}", e)
                    failureCount++
                }
            }

            android.util.Log.i("MapOverviewActivity", "路径绘制完成 - 成功：$successCount，失败：$failureCount")
            
            if (failureCount == paths.size) {
                Toast.makeText(this, "所有路径加载失败", Toast.LENGTH_SHORT).show()
            } else if (successCount > 0 && failureCount > 0) {
                Toast.makeText(this, "部分路径加载失败", Toast.LENGTH_SHORT).show()
            }

        } catch (e: Exception) {
            android.util.Log.e("MapOverviewActivity", "绘制路径过程失败", e)
            Toast.makeText(this, "绘制路径失败", Toast.LENGTH_SHORT).show()
        }
    }

    private fun getPointTypeListAndPoints() {
        RetrofitClient.apiService.getAllPointType().enqueue(object : Callback<UploadResponse<List<PointTypeData>>> {
            override fun onResponse(
                call: Call<UploadResponse<List<PointTypeData>>>,
                response: Response<UploadResponse<List<PointTypeData>>>
            ) {
                if (response.isSuccessful) {
                    response.body()?.data?.let {
                        pointTypeList = it.filter { type -> type != null && !type.typeName.isNullOrEmpty() }
                        getAllPoints()
                    }
                } else {
                    Toast.makeText(this@MapOverviewActivity, "获取点位类型失败", Toast.LENGTH_SHORT).show()
                }
            }
            override fun onFailure(call: Call<UploadResponse<List<PointTypeData>>>, t: Throwable) {
                Toast.makeText(this@MapOverviewActivity, "获取点位类型失败: ${t.message}", Toast.LENGTH_SHORT).show()
            }
        })
    }

    private fun getAllPoints() {
        RetrofitClient.apiService.getAllPoints().enqueue(object : Callback<UploadResponse<List<MapPoint>>> {
            override fun onResponse(
                call: Call<UploadResponse<List<MapPoint>>>,
                response: Response<UploadResponse<List<MapPoint>>>
            ) {
                if (response.isSuccessful) {
                    response.body()?.data?.let {
                        pointList.clear()
                        pointList.addAll(it)
                        drawAllPoints(pointList)
                    }
                } else {
                    Toast.makeText(this@MapOverviewActivity, "加载点位失败", Toast.LENGTH_SHORT).show()
                }
            }
            override fun onFailure(call: Call<UploadResponse<List<MapPoint>>>, t: Throwable) {
                Toast.makeText(this@MapOverviewActivity, "加载点位失败: ${t.message}", Toast.LENGTH_SHORT).show()
            }
        })
    }

    private fun drawAllPoints(points: List<MapPoint>) {
        // Don't clear the map here, as we want to preserve paths
        val executor = Executors.newSingleThreadExecutor()
        for (point in points) {
            val type = pointTypeList.find { it.id == point.typeId }
            if (type != null) {
                val iconUrl = type.typeIcon
                executor.execute {
                    try {
                        val future = Glide.with(this)
                            .asBitmap()
                            .load(iconUrl)
                            .submit(80, 80)
                        val bitmap = future.get()
                        runOnUiThread {
                            val markerOptions = MarkerOptions()
                                .position(LatLng(point.lat, point.lng))
                                .title(point.pointName)
                                .icon(BitmapDescriptorFactory.fromBitmap(bitmap))
                             //   .setExtraData(point) // 设置点位数据到marker中
                            val marker = aMap.addMarker(markerOptions)
                            markerMap[marker] = point


                        }
                    } catch (e: Exception) {
                        android.util.Log.e("MapOverviewActivity", "加载点位图标失败", e)
                    }
                }
            }
        }
        executor.shutdown()
    }

    override fun onResume() {
        super.onResume()
        binding.mapView.onResume()
    }
    
    override fun onPause() {
        super.onPause()
        binding.mapView.onPause()
    }
    
    override fun onDestroy() {
        super.onDestroy()
        binding.mapView.onDestroy()
        locationClient.onDestroy()
    }
    
    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        binding.mapView.onSaveInstanceState(outState)
    }
    override fun onOptionsItemSelected(item: android.view.MenuItem): Boolean {
        if (item.itemId == android.R.id.home) {
            onBackPressedDispatcher.onBackPressed()
            return true
        }
        return super.onOptionsItemSelected(item)
    }
    companion object {
        private const val PERMISSION_REQUEST_CODE = 100
    }
} 